#include "MainFrame/MenuBar/Dialogs/BlurDialog.h"
#include <QBoxLayout>
#include <QPushButton>

#include "Filters/RIVIABlur.h"
#include "MainFrame/CentralWidget/CentralManager.h"

#include <QSlider>
#include <QEvent>
#include <QLabel>
#include <QCheckBox>

BlurDialog::BlurDialog(QWidget *parent, Qt::WindowFlags f) :
    QDialog(parent, f),
    m_pButton(nullptr),
    m_pXSlider(nullptr),
    m_pYSlider(nullptr),
    m_pXLabel(nullptr),
    m_pYLabel(nullptr),
    m_pSyncCheckBox(nullptr),
    m_nX(1),
    m_nY(1)
{
    initDialog();
    connetSignalToSlots();
    initTrans();
}

BlurDialog::~BlurDialog()
{

}

void BlurDialog::initDialog()
{
    QVBoxLayout* layout = new QVBoxLayout(this);
    this->setLayout(layout);

    m_pSyncCheckBox = new QCheckBox(this);
    m_pSyncCheckBox->setChecked(true);

    m_pXLabel = new QLabel(this);
    m_pYLabel = new QLabel(this);
    m_pXSlider = new QSlider(Qt::Horizontal, this);
    m_pYSlider = new QSlider(Qt::Horizontal, this);
    m_pXSlider->setRange(1, 20);
    m_pYSlider->setRange(1, 20);

    layout->addWidget(m_pSyncCheckBox);
    layout->addWidget(m_pXLabel);
    layout->addWidget(m_pXSlider);
    layout->addWidget(m_pYLabel);
    layout->addWidget(m_pYSlider);

    m_pButton = new QPushButton(this);
    layout->addWidget(m_pButton);
}

void BlurDialog::connetSignalToSlots()
{
    connect(m_pXSlider, SIGNAL(valueChanged(int)), this, SLOT(blurXSlot(int)));
    connect(m_pYSlider, SIGNAL(valueChanged(int)), this, SLOT(blurYSlot(int)));
    connect(m_pButton, SIGNAL(pressed()), this, SLOT(confirmSlot()));
}

void BlurDialog::changeEvent(QEvent *event)
{
    QWidget::changeEvent(event);
    switch (event->type())
    {
    case QEvent::LanguageChange:
        initTrans();
        break;
    default:
        break;
    }
}

void BlurDialog::initTrans()
{
    this->setWindowTitle(tr("Blur"));

    m_pSyncCheckBox->setText(tr("Synchronized X and Y"));

    m_pXLabel->setText("X: 1");
    m_pYLabel->setText("Y: 1");

    m_pButton->setText(tr("Confirm"));
}

void BlurDialog::execBlur()
{
    RIVIABlur().blurWithGaussianBlur(m_nX*2-1, m_nY*2-1);
    CentralManager::updateImageViewWidget();
}

void BlurDialog::blurXSlot(int value)
{
    m_nX = value;
    if(m_pSyncCheckBox->isChecked())
    {
        m_nY = value;
        m_pYSlider->setValue(value);
    }
    m_pXLabel->setText("X: " + QString::number(m_nX*2-1));
    m_pYLabel->setText("Y: " + QString::number(m_nY*2-1));

    execBlur();
}

void BlurDialog::blurYSlot(int value)
{
    m_nY = value;
    if(m_pSyncCheckBox->isChecked())
    {
        m_nX = value;
        m_pXSlider->setValue(value);
    }
    m_pXLabel->setText("X: " + QString::number(m_nX*2-1));
    m_pYLabel->setText("Y: " + QString::number(m_nY*2-1));
    if(!m_pSyncCheckBox->isChecked())
        execBlur();
}

void BlurDialog::confirmSlot()
{
    RIVIABlur().finishBlur();
    this->close();
}
